<template>
    <el-card shadow="never" class="common-card">
        <template #header>
            <el-row justify="space-between" align="middle">
                <h2>类别管理</h2>
                <el-breadcrumb sepatrator="/">
                    <el-breadcrumb-item to="/control">控制台</el-breadcrumb-item>
                    <el-breadcrumb-item to="/control/user">类别管理</el-breadcrumb-item>
                    <el-breadcrumb-item>类别列表</el-breadcrumb-item>
                </el-breadcrumb>
            </el-row>
        </template>



        <div class="common-search">
            <el-form :inline="true" :module="queryForm" ref="queryFormRef">
                <el-form-item>
                    <el-button @click="delBatchByIds" type="danger" v-if="delIds.length > 0">批量删除</el-button>
                </el-form-item>
                <el-form-item>
                    <el-select style="width: 120px;" v-model.number="queryForm.status" placeholder="选择审核" clearable>
                        <el-option :value="1" label="未审核" />
                        <el-option :value="2" label="已审核" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="keyword">
                    <el-input style="width: 220px;" v-model.trim="queryForm.keyword" placeholder="请输入类别名称" clearable />
                </el-form-item>
            </el-form>
            <el-button align="right" type="primary" @click="openDialog()" :icon="Plus">新增</el-button>
        </div>

        <el-table ref="table" :data="searchData" border :loading="loading" row-key="id" 
        @selection-change="onselectionChange">
            <el-table-column type="selection" width="40" />
            <el-table-column label="类别名称" width="400" prop="name" v-model.trim="form.name" />
            <el-table-column label="排序" sortabel prop="orderId"></el-table-column>

            <el-table-column label="状态" width="110" prop="status" #default="scope">
                <span color="red" v-if="scope.row.status === 1">未审核</span>
                <span color="green" v-else-if="scope.row.status === 2">已审核</span>
            </el-table-column>

            <el-table-column label="创建时间" width="300" prop="createTime" #default="scope">
                <span>{{ moment(scope.row.createTime).format('YYYY年MM月DD日') }}</span>
            </el-table-column>

            <el-table-column label="操作" width="150" #default="scope" fixed="right">
                <el-button plain type="primary" size="small" @click="openDialog(scope.row.id)">修改</el-button>
                <el-button plain type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>


        <template #footer>
            <el-pagination background v-model:current-page="page" v-model:page-size="pageSize"
                :page-sizes="[2, 3, 4, 5, 6, 7, 8]" layout="total, sizes, prev, pager, next, jumper" />
        </template>
    </el-card>

    <Teleport to="body">
        <el-dialog v-model="dialogVisible" :title="`${$editId === 0 ? '新增' : '修改'}类别`" top="12vh" width="400px">
            <el-form label-width="100px" :model="form" ref="formRef" :rules="rules">
                <el-form-item label="所属类别" prop="parentId" width="150px">
                    <el-cascader style="width: 200px;" v-model="form.parentId" :options="[{ name: '一级类别', id: 0 }].concat(tableData)"
                        :props="{ label: 'name', value: 'id' , checkStrictly: true,emitPath:false}" placeholder="请选择所属类别"/>
                </el-form-item>
                <el-form-item label="类目名称" prop="name">
                    <el-input v-model.trim="form.name" placeholder="请输入类目名称" clearable />
                </el-form-item>
                <el-form-item label="排序号" prop="orderId" width="150px">
                    <el-input-number  prop="orderId" min="1" v-model.number="form.orderId" />
                </el-form-item>
                <el-form-item label="审核">
                    <el-switch v-model="form.status" :active-value="2" :inactive-value="1" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrEditCategory">确定</el-button>
                </div>
            </template>
        </el-dialog>

    </Teleport>
</template>

<script setup lang="ts">
import moment from 'moment';
import { Plus } from '@element-plus/icons-vue';
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { categoryAdd, categoryEdit, categoryAddOrEdit, categoryDel, categoryBatchDel, categoryList, categoryById } from '@/apis/category'
import type { ICategory } from '@/types';

const queryForm = reactive({
    status: '',
    keyword: ''
})
//分页 - 页码定义
const page = ref(1)
const pageSize = ref(4)

const delIds = ref<number[]>([]);

//查询 - 加载状态
const loading = ref(false)
const tableData = ref([])

const formRef = ref();
const dialogVisible = ref(false);

const form = reactive<ICategory>({
    name: '',
    id: 0,
    orderId: 0,
    parentId: 0,
    status: 0,
})

const rules = reactive({
  categoryId: { required: true, message: '请选择所属类别' },
  name: { required: true, message: '请输入类目名称' },
  orderId: { required: true, message: '请输入排序号' },
})


const queryFormRef = ref();

const searchData = computed(() => {
    const { status, keyword } = queryForm;
    return tableData.value.filter((item: ICategory) => {
        return (status ? item.status === Number(status) : true) && item.name.includes(keyword)
    })
})

const getCategoryList = async () => {
    try {
        const res = await categoryList();
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        tableData.value = res.data.data;
        console.log(tableData.value);
        loading.value = false;
    } catch (err) {
        ElMessage.error(JSON.stringify(err));
    }
}
getCategoryList();


const tableRef = ref();
const delBatchByIds = async () => {
  try {
    const yes = await ElMessageBox.confirm('您确定要删除所选信息吗？', '提示', { type: 'warning' });
    if (!yes) return;

    await categoryBatchDel(delIds.value);
    ElMessage.success('批量删除成功!');

    // 刷新页面
    getCategoryList();
  } catch (error) {
    if (error === 'cancel') {
      tableRef.value.clearSelection();
      return;
    }
    ElMessage.error(JSON.stringify(error));
  }
}

const delById = async (id: number) => {
    try {
        const yes = await ElMessageBox.confirm('您确定要删除此条信息？', '提示', { type: 'warning' });
        if (!yes) return;
        const res = await categoryDel(id);
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        ElMessage.success('删除成功');
        getCategoryList();
    } catch (err) {
        ElMessage.error(JSON.stringify(err))
    }
}


const $editId = ref(0);

const openDialog = async (editId: number = 0) => {
  $editId.value = editId;
  if (editId) {
    formRef.value?.clearValidate();
    try {
      const res = await categoryById(editId);
      if (res.data.code !== 0) {
        ElMessage.error(res.data.desc);
        return
      }
      form.id = res.data.data.id;
      form.status = res.data.data.status;
    } catch (err) {
      ElMessage.error(JSON.stringify(err));
    }
  } else {
    formRef.value?.resetFields();

 
    form.id = 0;
    form.status = 2;
  
  }
  dialogVisible.value = true;
}

const addOrEditCategory = async () => {
  try {
    // 表单校验
    const isValid = await formRef.value.validate();
    if (!isValid) return;

    // 新增或者修改
    const res = await categoryAddOrEdit(form);
    if (res.data.code !== 0) {
      ElMessage.error(res.data.desc);
      return;
    }
    ElMessage.success(form.id ? '修改成功!' : '新增成功!');

    // 刷新页面
    dialogVisible.value = false;
    getCategoryList();
  } catch (error) {
    if (typeof error === 'string') ElMessage.error(error);
    console.error(error);
  }
}

const onselectionChange = (val: ICategory[]) => {
    delIds.value = val.map((item: ICategory) => item.id) as number[]
}
</script>
